﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClipPlayer
{
    public class CSimpleConfig
    {
        public string HINT_FILE_NAME = ".ClipPlayer.hint";
        private string previousDirectory = "";
        private Dictionary<string, string> configData = new Dictionary<string, string>();

        public bool Load(string dirName)
        {
            if(0 == string.Compare(previousDirectory, dirName, true))
            {
                return true;
            }
            //
            try
            {
                if (!System.IO.Directory.Exists(dirName))
                {
                    configData.Clear(); previousDirectory = "";
                    return false;
                }
                string hintFile = System.IO.Path.Combine(dirName, HINT_FILE_NAME);
                if (!System.IO.File.Exists(hintFile))
                {
                    configData.Clear(); previousDirectory = "";
                    return false;
                }
                List<string> ll = System.IO.File.ReadLines(hintFile, Encoding.UTF8).ToList<string>();
                ll.ForEach(x => x.Trim());
                ll.Remove("");
                ll.RemoveAll(x => x.StartsWith("#"));
                ll.RemoveAll(x => x.StartsWith("//"));
                ll.RemoveAll(x => !x.Contains("="));
                if (0 == ll.Count())
                {
                    return false;
                }
                var keyValues = (from x in ll let pp = x.Split(new char[] { '=' }, 2) select new { key = pp[0].Trim().ToLower(), value = pp[1].Trim() }).ToList();
                keyValues.RemoveAll(x => "" == x.key);
                configData.Clear();

                keyValues.ForEach(x => configData.Add(x.key, x.value));
            }
            catch
            {
                configData.Clear(); previousDirectory = "";
                return false;
            }
            //
            previousDirectory = dirName;
            return true;
        }

        public string GetValueString(string key, string defaultValue="")
        {
            string value;
            if(configData.TryGetValue(key.ToLower(), out value))
            {
                return value;
            }
            return defaultValue;
        }
        public bool GetValueBool(string key, bool defaultValue = false)
        {
            string b = GetValueString(key).ToLower();
            //
            if ("" == b) return defaultValue;
            //
            if ("true" == b) return true;
            return false;
        }
    }//class
}//namespace
